package com.bf.electroplating.util.word;

import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ControlProblemRenovate;
import com.bf.electroplating.pojo.entity.ControlRenovateRectification;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ControlProblemRenovateService;
import com.bf.electroplating.service.ControlRenovateRectificationService;
import com.bf.electroplating.service.PubAttachmentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Word整改数据处理器
 * 负责处理Word文档中提取的整改数据并保存到数据库
 */
@Slf4j
@Component
public class WordRectificationDataProcessor {
    
    @Resource
    private ControlProblemRenovateService controlProblemRenovateService;
    
    @Resource
    private ControlRenovateRectificationService controlRenovateRectificationService;
    
    @Resource
    private PubAttachmentService pubAttachmentService;
    
    @Resource
    private ComCompanyService comCompanyService;
    
    /**
     * 处理Word文档数据
     * @param documentData Word文档数据
     * @param rowImageMap 行图片映射
     * @return 处理结果
     */
    @Transactional(rollbackFor = Exception.class)
    public WordProcessResult processDocument(WordDocumentParser.WordDocumentData documentData, 
                                           Map<String, String> rowImageMap) {
        WordProcessResult result = new WordProcessResult();
        result.setDocumentPath(documentData.getFilePath());
        result.setCompanyName(documentData.getCompanyName());
        
        if (documentData.hasError()) {
            result.setSuccess(false);
            result.setErrorMessage(documentData.getError());
            return result;
        }
        
        try {
            log.info("开始处理Word文档: {}, 公司: {}", 
                documentData.getFilePath(), documentData.getCompanyName());
            
            // 1. 尝试匹配企业信息
            ComCompany matchedCompany = matchCompanyByName(documentData.getCompanyName());
            if (matchedCompany != null) {
                log.info("匹配到企业: {} (ID: {})", matchedCompany.getCompanyName(), matchedCompany.getId());
            } else {
                log.warn("未找到匹配的企业: {}，将使用原始公司名称", documentData.getCompanyName());
            }
            
            List<Map<String, String>> tableData = documentData.getTableData();
            if (tableData == null || tableData.isEmpty()) {
                result.setSuccess(false);
                result.setErrorMessage("未找到表格数据");
                return result;
            }
            
            int successCount = 0;
            int failCount = 0;
            List<String> errors = new ArrayList<>();
            Map<String, Integer> errorStats = new HashMap<>(); // 错误统计
            
            // 处理每一行数据
            for (int i = 0; i < tableData.size(); i++) {
                Map<String, String> rowData = tableData.get(i);
                
                try {
                    // 转换为Word整改数据对象
                    WordRectificationData rectificationData = WordRectificationData.fromMap(
                        rowData, matchedCompany, documentData.getCompanyName());
                    
                    // 设置图片路径
                    String beforeImageKey = i + "_before";
                    String afterImageKey = i + "_after";
                    
                    if (rowImageMap.containsKey(beforeImageKey)) {
                        rectificationData.setBeforeImagePath(rowImageMap.get(beforeImageKey));
                    }
                    
                    if (rowImageMap.containsKey(afterImageKey)) {
                        rectificationData.setAfterImagePath(rowImageMap.get(afterImageKey));
                    }
                    
                    // 验证数据
                    if (!rectificationData.isValid()) {
                        String validationError = rectificationData.getValidationError();
                        String error = String.format("第%d行数据无效: %s", i + 1, validationError);
                        errors.add(error);
                        failCount++;
                        
                        // 统计错误类型
                        String errorType = "数据验证失败: " + validationError;
                        errorStats.put(errorType, errorStats.getOrDefault(errorType, 0) + 1);
                        
                        log.warn("跳过无效数据: {}", error);
                        continue;
                    }
                    
                    // 保存数据到数据库
                    saveRectificationData(rectificationData, matchedCompany, documentData.getCompanyName());
                    successCount++;
                    
                    log.info("✅ 处理成功: 第{}行 - {}", i + 1, rectificationData.getProblemLocation());
                    
                } catch (Exception e) {
                    String error = String.format("第%d行处理失败: %s", i + 1, e.getMessage());
                    errors.add(error);
                    failCount++;
                    
                    // 统计错误类型
                    String errorType = "处理异常: " + e.getClass().getSimpleName();
                    errorStats.put(errorType, errorStats.getOrDefault(errorType, 0) + 1);
                    
                    log.error("❌ 处理失败: 第{}行", i + 1, e);
                }
            }
            
            result.setSuccess(true);
            result.setSuccessCount(successCount);
            result.setFailCount(failCount);
            result.setErrors(errors);
            result.setErrorStats(errorStats);
            
            log.info("Word文档处理完成: 成功{}条，失败{}条", successCount, failCount);
            
            // 输出错误统计
            if (!errorStats.isEmpty()) {
                log.warn("错误统计:");
                for (Map.Entry<String, Integer> entry : errorStats.entrySet()) {
                    log.warn("  {}: {}次", entry.getKey(), entry.getValue());
                }
            }
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage("处理文档时发生异常: " + e.getMessage());
            log.error("处理Word文档异常", e);
        }
        
        return result;
    }
    
    /**
     * 匹配企业信息
     */
    private ComCompany matchCompanyByName(String companyName) {
        if (companyName == null || companyName.trim().isEmpty()) {
            return null;
        }
        
        try {
            // 1. 精确匹配
            ComCompany exactMatch = comCompanyService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ComCompany>()
                    .eq(ComCompany::getCompanyName, companyName.trim())
                    .eq(ComCompany::getDelFlag, "0")
            );
            
            if (exactMatch != null) {
                log.info("精确匹配到企业: {} -> {}", companyName, exactMatch.getCompanyName());
                return exactMatch;
            }
            
            // 2. 模糊匹配（包含关系）
            List<ComCompany> fuzzyMatches = comCompanyService.list(
                    new  com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ComCompany>()
                    .like(ComCompany::getCompanyName, companyName.trim())
                    .eq(ComCompany::getDelFlag, "0")
            );
            
            if (!fuzzyMatches.isEmpty()) {
                // 选择最匹配的（最短的匹配结果）
                ComCompany bestMatch = fuzzyMatches.stream()
                    .min((c1, c2) -> Integer.compare(c1.getCompanyName().length(), c2.getCompanyName().length()))
                    .orElse(null);
                
                if (bestMatch != null) {
                    log.info("模糊匹配到企业: {} -> {}", companyName, bestMatch.getCompanyName());
                    return bestMatch;
                }
            }
            
            // 3. 反向匹配（企业名称包含输入的公司名称）
            List<ComCompany> reverseMatches = comCompanyService.list(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ComCompany>()
                    .apply("company_name LIKE CONCAT('%', {0}, '%')", companyName.trim())
                    .eq(ComCompany::getDelFlag, "0")
            );
            
            if (!reverseMatches.isEmpty()) {
                ComCompany bestMatch = reverseMatches.stream()
                    .min((c1, c2) -> Integer.compare(c1.getCompanyName().length(), c2.getCompanyName().length()))
                    .orElse(null);
                
                if (bestMatch != null) {
                    log.info("反向匹配到企业: {} -> {}", companyName, bestMatch.getCompanyName());
                    return bestMatch;
                }
            }
            
            log.warn("未找到匹配的企业: {}", companyName);
            return null;
            
        } catch (Exception e) {
            log.error("匹配企业信息失败: {}", companyName, e);
            return null;
        }
    }
    
    /**
     * 保存整改数据到数据库
     */
    private void saveRectificationData(WordRectificationData data, ComCompany company, String originalCompanyName) {
        // 1. 创建整改问题记录
        ControlProblemRenovate renovate = new ControlProblemRenovate();
        renovate.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        renovate.setProblemLocation(data.getProblemLocation());
        renovate.setProblemDescription(data.getProblemDescription());
        renovate.setSuggest(data.getSuggestions());
        renovate.setRectificationStatus(data.getRectificationStatus());
        renovate.setParkId("1001"); // 默认园区ID
        renovate.setDelFlag("0");
        
        // 设置企业ID：如果匹配到企业则使用企业ID，否则使用原始公司名称
        if (company != null) {
            renovate.setCompanyId(company.getId());
            log.debug("使用匹配的企业ID: {} -> {}", company.getCompanyName(), company.getId());
        } else {
            // 使用原始公司名称作为标识，格式：word_公司名称
            String wordCompanyId = "word_" + originalCompanyName.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "_");
            renovate.setCompanyId(wordCompanyId);
            log.debug("使用原始公司名称作为ID: {} -> {}", originalCompanyName, wordCompanyId);
        }
        
        // 保存整改问题
        controlProblemRenovateService.save(renovate);
        log.debug("保存整改问题成功，ID={}", renovate.getId());
        
        // 2. 上传整改前照片
        if (data.hasBeforeImage()) {
            try {
                String beforeAttId = pubAttachmentService.uploadFileFromPath(
                    data.getBeforeImagePath(),
                    renovate.getId(),
                    AttModuleEnums.RENOVATE_PHOTO.getCode()
                );
                log.debug("整改前照片上传成功，附件ID={}", beforeAttId);
            } catch (Exception e) {
                log.error("整改前照片上传失败: {}", data.getBeforeImagePath(), e);
            }
        }
        
        // 3. 创建整改记录
        ControlRenovateRectification rectification = new ControlRenovateRectification();
        rectification.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        rectification.setRId(renovate.getId());
        rectification.setRectificationDescription(data.getRectificationContent());
        rectification.setRectificationTime(new Date());
        rectification.setDelFlag("0");
        
        // 保存整改记录
        controlRenovateRectificationService.save(rectification);
        log.debug("保存整改记录成功，ID={}", rectification.getId());
        
        // 4. 上传改造后照片
        if (data.hasAfterImage()) {
            try {
                String afterAttId = pubAttachmentService.uploadFileFromPath(
                    data.getAfterImagePath(),
                    rectification.getId(),
                    AttModuleEnums.RENOVATE_RECTIFICATION_PHOTO.getCode()
                );
                log.debug("改造后照片上传成功，附件ID={}", afterAttId);
            } catch (Exception e) {
                log.error("改造后照片上传失败: {}", data.getAfterImagePath(), e);
            }
        }
    }
    
    /**
     * 批量处理多个文档
     */
    public List<WordProcessResult> processDocuments(List<WordDocumentParser.WordDocumentData> documents, 
                                                   Map<String, Map<String, String>> allImageMaps) {
        List<WordProcessResult> results = new ArrayList<>();
        
        for (WordDocumentParser.WordDocumentData document : documents) {
            String documentPath = document.getFilePath();
            Map<String, String> rowImageMap = allImageMaps.getOrDefault(documentPath, new HashMap<>());
            
            WordProcessResult result = processDocument(document, rowImageMap);
            results.add(result);
        }
        
        return results;
    }
    
    /**
     * 获取企业匹配统计信息
     */
    public Map<String, Object> getCompanyMatchingStats(List<WordDocumentParser.WordDocumentData> documents) {
        Map<String, Object> stats = new HashMap<>();
        int matchedCount = 0;
        int unmatchedCount = 0;
        List<String> matchedCompanies = new ArrayList<>();
        List<String> unmatchedCompanies = new ArrayList<>();
        
        for (WordDocumentParser.WordDocumentData document : documents) {
            if (!document.hasError()) {
                ComCompany matchedCompany = matchCompanyByName(document.getCompanyName());
                if (matchedCompany != null) {
                    matchedCount++;
                    matchedCompanies.add(document.getCompanyName() + " -> " + matchedCompany.getCompanyName());
                } else {
                    unmatchedCount++;
                    unmatchedCompanies.add(document.getCompanyName());
                }
            }
        }
        
        stats.put("matchedCount", matchedCount);
        stats.put("unmatchedCount", unmatchedCount);
        stats.put("matchedCompanies", matchedCompanies);
        stats.put("unmatchedCompanies", unmatchedCompanies);
        
        return stats;
    }
    
    /**
     * Word处理结果
     */
    public static class WordProcessResult {
        private boolean success;
        private String documentPath;
        private String companyName;
        private int successCount;
        private int failCount;
        private List<String> errors;
        private Map<String, Integer> errorStats; // 错误统计
        private String errorMessage;
        
        // Getters and Setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public String getDocumentPath() { return documentPath; }
        public void setDocumentPath(String documentPath) { this.documentPath = documentPath; }
        
        public String getCompanyName() { return companyName; }
        public void setCompanyName(String companyName) { this.companyName = companyName; }
        
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        
        public int getFailCount() { return failCount; }
        public void setFailCount(int failCount) { this.failCount = failCount; }
        
        public List<String> getErrors() { return errors; }
        public void setErrors(List<String> errors) { this.errors = errors; }
        
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        
        public Map<String, Integer> getErrorStats() { return errorStats; }
        public void setErrorStats(Map<String, Integer> errorStats) { this.errorStats = errorStats; }
        
        public int getTotalCount() { return successCount + failCount; }
        
        @Override
        public String toString() {
            return String.format("WordProcessResult{成功=%s, 文档='%s', 公司='%s', 成功=%d条, 失败=%d条}", 
                success, documentPath, companyName, successCount, failCount);
        }
        
        /**
         * 获取处理摘要
         */
        public String getSummary() {
            if (success) {
                return String.format("✅ %s - 成功处理%d条数据", 
                    getFileName(), successCount);
            } else {
                return String.format("❌ %s - 处理失败: %s", 
                    getFileName(), errorMessage);
            }
        }
        
        /**
         * 获取文件名
         */
        public String getFileName() {
            if (documentPath == null) return "未知文件";
            int lastSlash = documentPath.lastIndexOf("/");
            int lastBackslash = documentPath.lastIndexOf("\\");
            int lastIndex = Math.max(lastSlash, lastBackslash);
            return lastIndex >= 0 ? documentPath.substring(lastIndex + 1) : documentPath;
        }
    }
}
